package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

//security框架授权和认证
@Component
public class SecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        User user = userService.findUserByName(username);
        if(user==null){
        //用户不存在直接返回null给权限用户
            return null;
        }
        //获取到用户所有的role
        Set<Role> roles = user.getRoles();
        List<GrantedAuthority> list = new ArrayList<>();
        //遍历所有的role
        for (Role role : roles) {
            //加入角色权限到框架中，框架会为当前用户赋予角色权限
            Integer id = role.getId();
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //查询每个用户所拥有的权限
            Set<Permission> permissions = role.getPermissions();
            //遍历权限集合
            for (Permission permission : permissions) {
//                Integer id1 = permission.getId();
                //将每一个权限加入框架，框架会为当前用户赋予权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //将查询出来的密码，前台用户名，权限集合 进行封装  security内部会帮我们进行用户名密码的校验
        System.out.println(bCryptPasswordEncoder.encode("123"));
        System.out.println(roles);
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return userDetails;
    }
}
